import axios from 'axios'
import useStore from '@/stores'
import { notification } from 'ant-design-vue'
import 'ant-design-vue/es/notification/style/css'
import router from '@/router'
import { getToken } from '@/utils/auth'
// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 节流白名单
let whiteList = ['']
// 节流
let pending = [] //声明一个数组用于存储每个ajax请求的取消函数和ajax标识
let cancelToken = axios.CancelToken //初始化取消请求的构造函数
let removePending = (config, f) => {
  let flagUrl = config.url
  // 不在白名单
  if (!whiteList.includes(flagUrl)) {
    if (pending.indexOf(flagUrl) !== -1) {
      if (f) {
        f()
      } else {
        pending.splice(pending.indexOf(flagUrl), 1)
      }
    } else {
      if (f) {
        pending.push(flagUrl)
      }
    }
  }
}
// request interceptor
service.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么--携带token
    if (getToken()) {
      config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    config.cancelToken = new cancelToken((c) => {
      // 重复提交的请求直接取消
      removePending(config, c)
    })
    return config
    // config.headers['Content-Type'] = 'application/json'
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    response.config.cancelToken = new cancelToken(() => {
      // 请求成功/失败，将该请求从节流名单中释放
      removePending(response.config)
    })
    // if the custom code is not 200, it is judged as an error.
    const status = response.status
    if (status !== 200) {
      notification.error({
        message: '提示',
        description: response.statusText || '抱歉，系统繁忙，请稍后重试！'
      })
      return Promise.reject('error')
    }
    const code = response.data.code
    if (code !== 1000) {
      notification.error({
        message: '提示',
        description: response.data.message || '抱歉，系统繁忙，请稍后重试！'
      })
      return Promise.reject('error')
    }
    /*const code = response.data.code;
    // 导出接口
    if (response.data instanceof Blob) {
      return response.data;
    } else if (code === 20004) {
      //验证码过期
      notification.error({
        message: "提示",
        description: response.data.message,
      });
      return response.data;
    } else if (code !== 10000) {
      // 请求成功，但接口报错
      notification.error({
        message: "提示",
        description: response.data.message
          ? response.data.message
          : "抱歉，系统繁忙，请稍后重试！",
      });
      return Promise.reject("error");
    }*/
    return response.data
  },
  (error) => {
    // let code = 0;
    try {
      error.response.config.cancelToken = new cancelToken(() => {
        // 请求成功/失败，将该请求从节流名单中释放
        removePending(error.response.config)
      })
      // code = error.response.data.code;
    } catch (e) {
      if (error.toString().indexOf('Error: timeout') !== -1) {
        notification.error({
          message: '提示',
          description: '网络请求超时'
        })
        return Promise.reject('error')
      }
      if (error.toString().indexOf('Error: Network Error') !== -1) {
        notification.error({
          message: '提示',
          description: '网络请求错误'
        })
        return Promise.reject('error')
      }
    }
    const { userStore } = useStore()

    /*if (code === 10002 || code === 10003) {
      // 令牌失效
      userStore.logout().then(() => {
        router.push({
          name: "login",
        });
      });
      return Promise.reject("error");
    } else if (code === 10004) {
      // 权限不足
      notification.error({
        message: "提示",
        description: error.response.data.message,
      });
      return Promise.reject("error");
    }*/
    notification.error({
      message: '错误提示',
      description: error.response.data.message || '抱歉，系统繁忙，请稍后重试！'
    })
    userStore.logout().then(() => {
      router.push({
        name: 'login'
      })
    })
    return Promise.reject('error')
  }
)

export default service
